from collections import Counter

import jieba
from django.shortcuts import render

# Create your views here.

from django.shortcuts import render
from django.http import HttpResponse
from .models import *
import os
from django.contrib import messages
from django.http import HttpResponseRedirect
from django.urls import reverse
import threading
import random
from random import randint
import pandas as pd
import time
import datetime
from datetime import datetime
from datetime import timedelta
from math import *
from .models import Danmu
from .models import GoodsInfo
from .models import LiveRecord
from .models import OrderDetails
from .models import OrderInfo
from .models import ZbInfo
from .models import LiveroomInfo
from .models import SalesInfo
import asyncio
import queue
from django.shortcuts import render
import json
from random import randrange

from django.http import HttpResponse
from rest_framework.views import APIView

from pyecharts.charts import Line
from pyecharts import options as opts
from pyecharts.charts import Bar
from pyecharts.globals import ThemeType
from pyecharts.faker import Faker
import jieba
from collections import Counter




ren4=list()
ren5=list()
ren6=list()
ren7=list()
ren8=list()

danmu4=list()
danmu5=list()
danmu6=list()
danmu7=list()
danmu8=list()

module_dir = os.path.dirname(__file__)
path = os.path.join(module_dir, '飞天狙想要努力变胖.csv')

def index_1(request):
    res={}##填入方框的数据
    if request.method == 'POST':
        name = request.POST.get('username')
        pwd = request.POST.get('password')
        tmp = EmployeeInfo.objects.filter(eid=name).exists()
        if tmp:  # 若表中存在该用户名数据，则已注册
            is_reg = EmployeeInfo.objects.filter(eid=name, psword=pwd).exists()
            if is_reg:  # 若查询有结果
                return render(request,'../templates/index.html')
            else:  # 若查询无结果，则用户名或密码错误
                res['rlt']  = '用户名或密码错误'
                return render(request, '../templates/login.html', res)
        else:  # 若表中无该用户名数据，则未注册
            res['rlt'] = '该用户名未注册，请注册后登录'
            return render(request, '../templates/login.html', res)
    else:
        return render(request, '../templates/index.html')


def login_view(request):
    return render(request,'../templates/login.html')

def register(request):#进入注册界面
    return render(request,'../templates/register.html')

def create(request):##注册并登录界面，
    if request.method == 'POST':
        res = {}
        username = request.POST['username']
        userpwd = request.POST['pwd']
        name=request.POST['name']
        depart=request.POST['depart']
        tmp = EmployeeInfo.objects.filter(eid=username).exists()
        if tmp:  # 若存在该用户名相关数据，则用户已注册
            res['rlt'] = '该用户名已注册'
            return render(request,'../templates/register.html',res)
        else:  # 用户未注册，则向数据库中插入数据
            EmployeeInfo.objects.create(eid=username, ename=name,psword=userpwd,etype=depart)
            res['rlt'] = '注册成功并登录'
            return render(request,'../templates/index.html')
    else:
        return render(request,'../templates/register.html')


def proc_index(request):
    return render(request, '../templates/Procurement/index.html')

def Warehouse_index(request):
    return render(request, '../templates/Warehouse/index.html')

def Stream_info(request):
    itemid=0
    sql_cmd = "select live_record_id from live_record order by live_record_id"
    for item in LiveRecord.objects.raw(sql_cmd):
        itemid = int(item.live_record_id[5:])
    itemid += 1
    return render(request, '../templates/live-info.html', {"record_id": itemid})
def tim(request):
    if request.method == 'POST':
        res = {}
        live_id = request.POST['liveroom_id']
        eid = request.POST['eid']
        start = " ".join(request.POST['live_starttime'].split("T"))+":00"
        end = " ".join(request.POST['live_endtime'].split("T"))+":00"
        record_id = request.POST['live_record_id']
        print(f"{ live_id} {eid} {record_id} {start} {end}")
        LiveroomInfo.objects.filter(liveroom_id=live_id).update(liveroom_status=1)
        if live_id=='ZBJ1234':
            Jbj4Renqi.objects.all().delete()#将表内数据清空
            j4=live(4,path,record_id,live_id,eid,start,end)
            asyncio.run(j4.main())
            messages.info(request, '开始监控直播')
            return HttpResponseRedirect(reverse('index'))

        elif live_id == 'ZBJ1235':
            Jbj5Renqi.objects.all().delete()
            j5 = live(5,path,record_id, live_id, eid, start, end)
            asyncio.run(j5.main())
            messages.info(request, '开始监控直播')
            return HttpResponseRedirect(reverse('index'))


        elif live_id == 'ZBJ1236':
            Jbj6Renqi.objects.all().delete()
            j6 = live(6,path,record_id, live_id, eid, start, end)
            asyncio.run(j6.main())
            messages.info(request, '开始监控直播')
            return HttpResponseRedirect(reverse('index'))


        elif live_id == 'ZBJ1237':
            Jbj7Renqi.objects.all().delete()
            j7 = live(7,path,record_id, live_id, eid, start, end)
            asyncio.run(j7.main())
            messages.info(request, '开始监控直播')
            return HttpResponseRedirect(reverse('index'))

        elif live_id == 'ZBJ1238':
            Jbj8Renqi.objects.all().delete()
            j8 = live(8,path, record_id, live_id, eid, start, end)
            asyncio.run(j8.main())
            messages.info(request, '开始监控直播')
            return HttpResponseRedirect(reverse('index'))


        else:
            res={}
            res['rlt']="抱歉,不存在该直播间，请核查待填写信息并重新填写"
            return render(request,"../templates/live-info.html",res)
        #return Stream_info(request)

def my_view(request):
    # 创建一个新的线程
    t = threading.Thread(target=tim,args=(request,))
    # 设置为守护线程，不会阻塞主线程退出
    t.setDaemon(True)
    # 启动线程
    t.start()
    # 使用render函数渲染一个模板文件，传入一些变量
    return render(request, "../templates/start.html")


class live:
    def __init__(self,ID,path,record,live_nu,host,start,end):
        global danmu5,danmu6,danmu7,danmu8,danmu4,ren4,ren5,ren6,ren7,ren8
        if ID==4:
            danmu4=[]
            ren4=[]
            self.d=danmu4
            self.ren=ren4
        elif ID==5:
            danmu5=[]
            ren5=[]
            self.d = danmu5
            self.ren = ren5
        elif ID == 6:
            danmu6=[]
            ren6=[]
            self.d = danmu6
            self.ren = ren6
        elif ID==7:
            danmu7=[]
            ren7=[]
            self.d = danmu7
            self.ren = ren7
        elif ID==8:
            danmu8=[]
            ren8=[]
            self.d = danmu8
            self.ren = ren8
        self.record=record# 直播记录号
        self.live_nu=live_nu#直播间号
        self.host=host#主播号
        self.start=datetime.strptime(start,'%Y-%m-%d %H:%M:%S')
        self.end=datetime.strptime(end,'%Y-%m-%d %H:%M:%S')
        df=pd.read_csv(path)
        self.danmu=list(df['弹幕数据'])
        self.guest=list(df['用户名'])
        ho=ZbInfo.objects.get(eid=host)
        live=LiveroomInfo.objects.get(liveroom_id=live_nu)
        LiveRecord.objects.create(live_record_id=record,liveroom=live,eid=ho,live_starttime=self.start,live_endtime=self.end)

    async def create_danmu(self):
        le=len(self.danmu)#记录弹幕数量，准备生成循环
        sign=0
        now=self.start
        sec=1
        self.dan=[]#生成一个记录列表，之后可以想想办法插入
        re = self.record
        while(now<self.end):#循环生成一个
            tim = (now + timedelta(seconds=sec)).strftime("%Y-%m-%d %H:%M:%S")
            id=self.record+str(sign).rjust(10, '0')
            ge=self.guest[sign]
            dn=self.danmu[sign]
            self.d.append(dn)
            await asyncio.sleep(sec)
            Danmu.objects.create(dm_id=id,live_record_id=re,user_name=ge,send_time=tim,send_text=dn)
            sec=randint(1,3)#弹幕发送的随机间隔
            sign=(sign+1)%le
            now= now + timedelta(seconds=sec)

    async def renshu(self):
        self.peo=[]
        self.peo_tim=[]
        renshu=1
        x=1#为了妥善的模拟人数变化，采用函数来表现趋势，2小时7200秒
        sec = 1
        now = self.start
        re = self.record
        lis = self._y()
        while (now < self.end):  # 循环生成一个
            ren={}
            ren['人数']=renshu
            ren['时间']=now.strftime("%Y-%m-%d %H:%M:%S")
            self.ren.append(ren)
            await asyncio.sleep(sec)
            renshu=lis[x]
            sec = 2  # 弹幕发送的随机间隔
            x=x+sec*2
            now = now + timedelta(seconds=sec)



    async def ding_dan(self):
        now = self.start
        N=randint(10,20)
        now = now + timedelta(seconds=N)
        m=1
        while (now < self.end):
            di={}
            di['订单编号']=self.record+str(m).rjust(7, '0')
            di['直播记录号']=self.record
            di['下单时间']=now.strftime("%Y-%m-%d %H:%M:%S")
            await asyncio.sleep(N)
            price = 0
            n = randint(1, 4)
            li = list(GoodsInfo.objects.all().values('goods_id', 'gprice'))
            #print(li)
            for i in range(n):  # 随机个商品
                #print(i)
                lens = len(li)
                #print(lens)
                item = li.pop(randint(0, lens - 1))
                #print(item)
                iid = item['goods_id']
                #print(iid)
                #print(item['gprice'])
                num = randint(1, 10)
                #print(num)
                price = price + num * int(item['gprice'])
                OrderDetails.objects.create(order_id=di['订单编号'],goods_id=iid,goods_num=num)
            gu=''.join(random.sample('ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890',10))
            #print(gu)
            #print(price)
            liiii=["SA42376","SA42377","SA42378","SA42379","SA42380","SA42381","SA42382","SA42383","SA42384","SA42385"]
            sta = ["未处理","未处理","未处理","未处理","未处理","退单"]
            xxx=random.choice(liiii)
            yyy = random.choice(sta)
            e=SalesInfo.objects.get(eid=xxx)
            OrderInfo.objects.create(order_id=di['订单编号'],live_record_id=self.record,cid=gu,eid=e,order_time=di['下单时间'],address="北京市",sum_price=price,process_status=yyy)
            #print("插入一条订单")
            N = randint(10, 30)
            m+=1
            now = now + timedelta(seconds=N)

    def random_walk(self,n):
        # n is the length of the sequence
        sequence = []  # empty list to store the values
        value = random.randint(35000, 50000)  # initial value between 40000 and 50000
        for i in range(n):
            step = random.randint(-500, 500)  # random step between -1 and 1
            value += step  # add the step to the current value
            value = max(35000, min(50000, value))  # limit the value between 40000 and 50000
            sequence.append(value)  # append the value to the list
        return sequence  # return the list

    def _y(self):
        lis1 = [random.randint(i, i + 5000) for i in range(0, 45000, 450)]
        lis2 = self.random_walk(3300)
        lis = lis1 + lis2
        return (lis)

        # return ceil(random.uniform(0,1)*(5000-x)+randint(-500,300))#生成一个随机的y

    def main(self):
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        future = asyncio.gather(self.create_danmu(), self.renshu(),self.ding_dan())
        loop.run_until_complete(future)


def response_as_json(data):
    json_str = json.dumps(data)
    response = HttpResponse(
        json_str,
        content_type="application/json",
    )
    response["Access-Control-Allow-Origin"] = "*"
    return response


def json_response(data, code=200):
    data = {
        "code": code,
        "msg": "success",
        "data": data,
    }
    return response_as_json(data)


def json_error(error_string="error", code=500, **kwargs):
    data = {
        "code": code,
        "msg": error_string,
        "data": {}
    }
    data.update(kwargs)
    return response_as_json(data)


JsonResponse = json_response
JsonError = json_error


def line_base4() -> Line:##表示生成数据的函数,此时输入的是一个静态的数据
    line = (
        Line()
        .add_xaxis([])
        .add_yaxis(series_name="", y_axis=[])
        .set_global_opts(
            title_opts=opts.TitleOpts(title="直播间人数"),
            xaxis_opts=opts.AxisOpts(type_="value"),
            yaxis_opts=opts.AxisOpts(type_="value")
        )
        .dump_options_with_quotes()
    )
    return line


class ChartView4(APIView):##生成一个展示数据的，用于交互的json文件，导入html
    def get(self, request, *args, **kwargs):
        return JsonResponse(json.loads(line_base4()))


class ChartUpdateView4(APIView):#通过该函数进行动态输入
    def get(self, request, *args, **kwargs):
        try:
            s=ren4.pop(-1)
            print(s)
            return JsonResponse({"name": s["时间"], "value": s["人数"]})
        except:
            s={"时间":0,"人数":0}
            return JsonResponse({"name": s["时间"], "value": s["人数"]})

def home_page4(request):#返回展示数据的模板
    return render(request,'../templates/Pye_chart/test.html',{})

def line_base5() -> Line:##表示生成数据的函数,此时输入的是一个静态的数据
    line = (
        Line()
        .add_xaxis([])
        .add_yaxis(series_name="", y_axis=[])
        .set_global_opts(
            title_opts=opts.TitleOpts(title="直播间人数"),
            xaxis_opts=opts.AxisOpts(type_="value"),
            yaxis_opts=opts.AxisOpts(type_="value")
        )
        .dump_options_with_quotes()
    )
    return line


class ChartView5(APIView):##生成一个展示数据的，用于交互的json文件，导入html
    def get(self, request, *args, **kwargs):
        return JsonResponse(json.loads(line_base5()))


class ChartUpdateView5(APIView):#通过该函数进行动态输入
    def get(self, request, *args, **kwargs):
        try:
            s=ren5.pop(-1)
            print(s)
            return JsonResponse({"name": s["时间"], "value": s["人数"]})
        except:
            s={"时间":0,"人数":0}
            return JsonResponse({"name": s["时间"], "value": s["人数"]})
def home_page5(request):#返回展示数据的模板
    return render(request,'../templates/Pye_chart/test5.html',{})

def line_base6() -> Line:##表示生成数据的函数,此时输入的是一个静态的数据
    line = (
        Line()
        .add_xaxis([])
        .add_yaxis(series_name="", y_axis=[])
        .set_global_opts(
            title_opts=opts.TitleOpts(title="直播间人数"),
            xaxis_opts=opts.AxisOpts(type_="value"),
            yaxis_opts=opts.AxisOpts(type_="value")
        )
        .dump_options_with_quotes()
    )
    return line


class ChartView6(APIView):##生成一个展示数据的，用于交互的json文件，导入html
    def get(self, request, *args, **kwargs):
        return JsonResponse(json.loads(line_base6()))


class ChartUpdateView6(APIView):#通过该函数进行动态输入
    def get(self, request, *args, **kwargs):
        try:
            s=ren6.pop(-1)
            print(s)
            return JsonResponse({"name": s["时间"], "value": s["人数"]})
        except:
            s={"时间":0,"人数":0}
            return JsonResponse({"name": s["时间"], "value": s["人数"]})

def home_page6(request):#返回展示数据的模板
    return render(request,'../templates/Pye_chart/test6.html',{})

def line_base7() -> Line:##表示生成数据的函数,此时输入的是一个静态的数据
    line = (
        Line()
        .add_xaxis([])
        .add_yaxis(series_name="", y_axis=[])
        .set_global_opts(
            title_opts=opts.TitleOpts(title="直播间人数"),
            xaxis_opts=opts.AxisOpts(type_="value"),
            yaxis_opts=opts.AxisOpts(type_="value")
        )
        .dump_options_with_quotes()
    )
    return line


class ChartView7(APIView):##生成一个展示数据的，用于交互的json文件，导入html
    def get(self, request, *args, **kwargs):
        return JsonResponse(json.loads(line_base7()))


class ChartUpdateView7(APIView):#通过该函数进行动态输入
    def get(self, request, *args, **kwargs):
        try:
            s=ren7.pop(-1)
            print(s)
            return JsonResponse({"name": s["时间"], "value": s["人数"]})
        except:
            s={"时间":0,"人数":0}
            return JsonResponse({"name": s["时间"], "value": s["人数"]})

def home_page7(request):#返回展示数据的模板
    return render(request,'../templates/Pye_chart/test7.html',{})

def line_base8() -> Line:##表示生成数据的函数,此时输入的是一个静态的数据
    line = (
        Line()
        .add_xaxis([])
        .add_yaxis(series_name="", y_axis=[])
        .set_global_opts(
            title_opts=opts.TitleOpts(title="直播间人数"),
            xaxis_opts=opts.AxisOpts(type_="value"),
            yaxis_opts=opts.AxisOpts(type_="value")
        )
        .dump_options_with_quotes()
    )
    return line


class ChartView8(APIView):##生成一个展示数据的，用于交互的json文件，导入html
    def get(self, request, *args, **kwargs):
        return JsonResponse(json.loads(line_base8()))


class ChartUpdateView8(APIView):#通过该函数进行动态输入
    def get(self, request, *args, **kwargs):
        try:
            s=ren8.pop(-1)
            print(s)
            return JsonResponse({"name": s["时间"], "value": s["人数"]})
        except:
            s={"时间":0,"人数":0}
            return JsonResponse({"name": s["时间"], "value": s["人数"]})

def home_page8(request):#返回展示数据的模板
    return render(request,'../templates/Pye_chart/test8.html',{})








def bar_base4() -> Bar:##表示生成数据的函数,此时输入的是一个静态的数据
    text=""
    le=len(danmu4)
    for i in range(le):
        text=text+danmu4.pop(0)
        # 如果文本不为空，生成词云图并保存为图片文件
    words = jieba.lcut(text)
    counter = Counter(words)
    top10 = counter.most_common(10)
    print(top10)
    words = [item[0] for item in top10]  # 提取词语
    freqs = [item[1] for item in top10]  # 提取频数
    bar = (
        Bar(init_opts=opts.InitOpts(theme=ThemeType.DARK))
        .add_xaxis(words)
        .add_yaxis("词频", freqs, itemstyle_opts=opts.ItemStyleOpts(color="#00CD96"))  # 自定义颜色
        .set_global_opts(
            title_opts={"text": "弹幕关键词前10"},
            brush_opts=opts.BrushOpts(),  # 设置操作图表的画笔功能
            toolbox_opts=opts.ToolboxOpts(),  # 设置操作图表的工具箱功能
            yaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(formatter="词频"), name="Y轴名称"),
            # 设置Y轴名称、定制化刻度单位
            xaxis_opts=opts.AxisOpts(name="X轴名称"), ) # 设置X轴名称
        .dump_options_with_quotes()
    )
    return bar


class ChartView_bar4(APIView):##生成一个展示数据的，用于交互的json文件，导入html
    def get(self, request, *args, **kwargs):
        return JsonResponse(json.loads(bar_base4()))

def bar_page4(request):#返回展示数据的模板
    return render(request,'../templates/graph/test_graph_1.html',{})

def bar_base5() -> Bar:##表示生成数据的函数,此时输入的是一个静态的数据
    text=""
    le=len(danmu5)
    for i in range(le):
        text=text+danmu5.pop(0)
        # 如果文本不为空，生成词云图并保存为图片文件
    words = jieba.lcut(text)
    counter = Counter(words)
    top10 = counter.most_common(10)
    print(top10)
    words = [item[0] for item in top10]  # 提取词语
    freqs = [item[1] for item in top10]  # 提取频数
    bar = (
        Bar(init_opts=opts.InitOpts(theme=ThemeType.DARK))
        .add_xaxis(words)
        .add_yaxis("词频", freqs, itemstyle_opts=opts.ItemStyleOpts(color="#00CD96"))  # 自定义颜色
        .set_global_opts(
            title_opts={"text": "弹幕关键词前10"},
            brush_opts=opts.BrushOpts(),  # 设置操作图表的画笔功能
            toolbox_opts=opts.ToolboxOpts(),  # 设置操作图表的工具箱功能
            yaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(formatter="词频"), name="Y轴名称"),
            # 设置Y轴名称、定制化刻度单位
            xaxis_opts=opts.AxisOpts(name="X轴名称"), ) # 设置X轴名称
        .dump_options_with_quotes()
    )
    return bar


class ChartView_bar5(APIView):##生成一个展示数据的，用于交互的json文件，导入html
    def get(self, request, *args, **kwargs):
        return JsonResponse(json.loads(bar_base5()))

def bar_page5(request):#返回展示数据的模板
    return render(request,'../templates/graph/test_graph_2.html',{})

def bar_base6() -> Bar:##表示生成数据的函数,此时输入的是一个静态的数据
    text=""
    le=len(danmu6)
    for i in range(le):
        text=text+danmu6.pop(0)
        # 如果文本不为空，生成词云图并保存为图片文件
    words = jieba.lcut(text)
    counter = Counter(words)
    top10 = counter.most_common(10)
    print(top10)
    words = [item[0] for item in top10]  # 提取词语
    freqs = [item[1] for item in top10]  # 提取频数
    bar = (
        Bar(init_opts=opts.InitOpts(theme=ThemeType.DARK))
        .add_xaxis(words)
        .add_yaxis("词频", freqs, itemstyle_opts=opts.ItemStyleOpts(color="#00CD96"))  # 自定义颜色
        .set_global_opts(
            title_opts={"text": "弹幕关键词前10"},
            brush_opts=opts.BrushOpts(),  # 设置操作图表的画笔功能
            toolbox_opts=opts.ToolboxOpts(),  # 设置操作图表的工具箱功能
            yaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(formatter="词频"), name="Y轴名称"),
            # 设置Y轴名称、定制化刻度单位
            xaxis_opts=opts.AxisOpts(name="X轴名称"), ) # 设置X轴名称
        .dump_options_with_quotes()
    )
    return bar


class ChartView_bar6(APIView):##生成一个展示数据的，用于交互的json文件，导入html
    def get(self, request, *args, **kwargs):
        return JsonResponse(json.loads(bar_base6()))

def bar_page6(request):#返回展示数据的模板
    return render(request,'../templates/graph/test_graph_3.html',{})

def bar_base7() -> Bar:##表示生成数据的函数,此时输入的是一个静态的数据
    text=""
    le=len(danmu7)
    for i in range(le):
        text=text+danmu7.pop(0)
        # 如果文本不为空，生成词云图并保存为图片文件
    words = jieba.lcut(text)
    counter = Counter(words)
    top10 = counter.most_common(10)
    print(top10)
    words = [item[0] for item in top10]  # 提取词语
    freqs = [item[1] for item in top10]  # 提取频数
    bar = (
        Bar(init_opts=opts.InitOpts(theme=ThemeType.DARK))
        .add_xaxis(words)
        .add_yaxis("词频", freqs, itemstyle_opts=opts.ItemStyleOpts(color="#00CD96"))  # 自定义颜色
        .set_global_opts(
            title_opts={"text": "弹幕关键词前10"},
            brush_opts=opts.BrushOpts(),  # 设置操作图表的画笔功能
            toolbox_opts=opts.ToolboxOpts(),  # 设置操作图表的工具箱功能
            yaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(formatter="词频"), name="Y轴名称"),
            # 设置Y轴名称、定制化刻度单位
            xaxis_opts=opts.AxisOpts(name="X轴名称"), ) # 设置X轴名称
        .dump_options_with_quotes()
    )
    return bar


class ChartView_bar7(APIView):##生成一个展示数据的，用于交互的json文件，导入html
    def get(self, request, *args, **kwargs):
        return JsonResponse(json.loads(bar_base7()))

def bar_page7(request):#返回展示数据的模板
    return render(request,'../templates/graph/test_graph_4.html',{})

def bar_base8() -> Bar:##表示生成数据的函数,此时输入的是一个静态的数据
    text=""
    le=len(danmu8)
    for i in range(le):
        text=text+danmu8.pop(0)
        # 如果文本不为空，生成词云图并保存为图片文件
    words = jieba.lcut(text)
    counter = Counter(words)
    top10 = counter.most_common(10)
    print(top10)
    words = [item[0] for item in top10]  # 提取词语
    freqs = [item[1] for item in top10]  # 提取频数
    bar = (
        Bar(init_opts=opts.InitOpts(theme=ThemeType.DARK))
        .add_xaxis(words)
        .add_yaxis("词频", freqs, itemstyle_opts=opts.ItemStyleOpts(color="#00CD96"))  # 自定义颜色
        .set_global_opts(
            title_opts={"text": "弹幕关键词前10"},
            brush_opts=opts.BrushOpts(),  # 设置操作图表的画笔功能
            toolbox_opts=opts.ToolboxOpts(),  # 设置操作图表的工具箱功能
            yaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(formatter="词频"), name="Y轴名称"),
            # 设置Y轴名称、定制化刻度单位
            xaxis_opts=opts.AxisOpts(name="X轴名称"), ) # 设置X轴名称
        .dump_options_with_quotes()
    )
    return bar


class ChartView_bar8(APIView):##生成一个展示数据的，用于交互的json文件，导入html
    def get(self, request, *args, **kwargs):
        return JsonResponse(json.loads(bar_base8()))

def bar_page8(request):#返回展示数据的模板
    return render(request,'../templates/graph/test_graph_5.html',{})